package org.android.pasos.activities.firstview;

import org.android.pasos.Constants;
import org.android.pasos.DatosTrama;
import org.android.pasos.R;
import org.android.pasos.util.UtilJSON;
import org.android.pasos.util.UtilTrama;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;

public class EmergencyActivity extends Activity {
	Intent intent = null;
	private ProgressDialog progressDialog;
	private AlertDialog.Builder alertDialog;
	private SharedPreferences mPrefs;

	// Handler para actualizar la UI una vez que acabe el background Thread
	private final Handler handler = new Handler() {

		@Override
		public void handleMessage(final Message msg) {
			progressDialog.dismiss();
			alertDialog.show();
		}

	};

	/** Called when the activity is first created. */

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.emergency);

		mPrefs = getSharedPreferences("PasosPreferences", MODE_PRIVATE);

		alertDialog = new AlertDialog.Builder(this)
				.setMessage(R.string.enviadaInformacion).setPositiveButton(
						"Ok", mDespedidaListener);

		this.progressDialog = ProgressDialog.show(this, getString(R.string.enviando),
				getString(R.string.informando_serv), true, false);

		// Las consultas REST hay que hacerlas en hilos no bloqueantes
		new Thread() {
			public void run() {
				// Se envia la peticion REST al servidor
				DatosTrama dt = UtilTrama.creartrama(getApplicationContext());
				UtilJSON.enviarIncidencia(getApplicationContext(), Constants.URL_INCIDENCIAS_REST,
						Constants.PERDIDA, dt);
				handler.sendEmptyMessage(0);
			}
		}.start();
	}

	OnClickListener mDespedidaListener = new OnClickListener() {

		public void onClick(DialogInterface dialog, int which) {
			Intent intent = new Intent(Constants.INTENT_MENU_PRINCIPAL);
			startActivity(intent);
		}
	};

	/*** Este metodo realiza una llamada automatica al 112 **/
	private void avisarEmergencias() {
		String uri = "tel:112";
		// Intent call = new Intent(Intent.ACTION_CALL);
		Intent call = new Intent(Intent.ACTION_DIAL);
		call.setData(Uri.parse(uri));
		// startActivity(call);
	}
}
